import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
from tools.config import ROOT_CONFIG
from tools.content import markdown, text, at


class Robot:
    """
        钉钉机器人
        webhook：机器人网址（有access_token）
        secret：机器人加签模式的签名
    """

    def __init__(self, access_token, secret=None) -> None:
        url = f"https://oapi.dingtalk.com/robot/send?access_token={access_token}"

        if secret:  # 签名不为空，需要生成签名（钉钉要求）
            timestamp = str(round(time.time() * 1000))
            string_to_sign = f'{timestamp}\n{secret}'
            hmac_code = hmac.new(secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()
            sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
            url = url + f"&timestamp={timestamp}&sign={sign}"

        self.__url = url

    def __body_setting(self, body_type):  # 设置机器人发送信息 只使用文本类型和markdown类型
        # 根据msgtype是text还是markdown选择使用text参数或markdown参数
        if body_type == "markdown":
            self.__body = {"msgtype": "markdown",
                           "markdown": markdown,
                           "at": at
                           }

        self.__body = {"msgtype": "text",
                       "text": text,
                       "at": at
                       }

    def send_dingtalk_message(self, body_type):
        self.__body_setting(body_type=body_type)
        headers = {"Content-Type": "application/json"}
        resp = requests.post(self.__url, json=self.__body, headers=headers)
        print("发送成功" if resp.json().get("errcode") == 0 else "发送失败")

        # 发送后返回两个值
        # 发送成功，errmsg值是"ok"，errcode值是0
        # errcode是错误码，errmsg是错误描述
        print(resp.json().get("errmsg"), resp.json().get("errcode"))
        return resp


if __name__ == "__main__":
    access_token = ROOT_CONFIG["QFinanceGridModel_RT01"]["access_token"]
    secret = ROOT_CONFIG["QFinanceGridModel_RT01"]["secret"]
    robot = Robot(access_token, secret)
    resp = robot.send_dingtalk_message(body_type="text")
    print(resp)
